<template>
	<view class="container">
		<!-- 最近会话 -->
		 <uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text" activeColor="#55aaff"></uni-segmented-control>
		  <view class="content">
		            <view v-show="current === 0">
		           		<view class="section" >
		           			<view class="section-header">
		           				<view class="section-title">最近会话</view>
		           				<view class="sort-actions">
		           					<text v-if="isDelCount" class="sort-btn del-btn"  @click="delCount">删除</text>
		           					<text class="sort-btn time-btn" @click="handleSort('time')">时间</text>
		           					<text class="sort-btn unread-btn" :class="{ active: unreadView }" @click="handleSort('unread')">未读</text>
		           				</view>
		           			</view>
		           			<!-- 加载态骨架屏 -->
		           			<view v-if="!isReadyNic" class="loading-skeleton">
		           				<view class="skeleton-item" v-for="(i, idx) in 5" :key="idx"></view>
		           			</view>
		           			<scroll-view v-else-if="chatListView.length > 0" class="recent-list" scroll-y="true" :style="{ height: listHeight }">
		           		
		           					<view
		           						class="recent-item"
		           						v-for="(item, index) in chatView"
		           						:key="`chat_${item.userId}_${item.type}`" 
		           						@longpress="handleLongPressChat(item.userId)"
		           						@click="!isDelCount && handleContactClick(item.userId, item.type)"
		           						:class="{ active: item.userId===userId }"
		           					>
		           					
		           						<view class="avatar-container">
		           							<view v-if="!item.pic" class="avatar-loading">
		           								<uni-icons type="spinner" size="24" color="#ccc" spin></uni-icons>
		           							</view>
		           							<image v-else class="avatar" :src="item.pic.url" mode="aspectFill" lazy-load></image>
		           							<view v-if="item.unreadCount > 0" class="badge">
		           								{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
		           							</view>
		           						</view>
		           						<view class="name-msg-wrapper">
		           							<view class="name-row">
		           								<text class="name" v-text="item.name"></text>
		           								<text class="time" v-text="formatMessageTime(item.lastMessage.timestamp)"></text>
		           							</view>
		           							<text class="msg" :class="{ unread: item.unreadCount > 0 }" v-text="item.content"></text>
		           						</view>
		           					</view>
		           		
		           			</scroll-view>
		           			<!-- 空状态 -->
		           			<view v-else class="empty-state">
		           				<uni-icons type="chat-empty" size="60" color="#ccc"></uni-icons>
		           				<text class="empty-text">暂无会话记录</text>
		           				<text class="empty-tip">点击联系人开始聊天吧~</text>
		           			</view>
		           		</view>
		            </view>
		            <view v-show="current === 1">
		              		<view class="section" >
		              			<view class="section-header">
		              				<view class="section-title">群、位置收藏（{{ favoriteList.length }}）</view>
		              				<view class="sort-actions">
		              					<text v-if="isDelFavorite" class="sort-btn del-btn"  @click="handleDelfavo">删除</text>
		              					<text class="sort-btn" @click="handleSort('距离')">距离</text>
		              					<text class="sort-btn" @click="handleSort('alpha')">A-Z</text>
		              				</view>
		              			</view>
		              			<scroll-view class="recent-list" scroll-y="true" :style="{ height: listHeight }">
		              		
		              					<view
		              						class="recent-item"
		              						v-for="(item, index) in favoriteList"
		              						:key="`favor_${item.favorite_id}`" 
		              						@longpress="handleLongPress(item.favorite_id)"
		              						@click="!isDelFavorite && handlefavorite(item)"
		              						:class="{ active: favorite_id===item.favorite_id }"
		              					>
		              					
		              						<view class="avatar-container">
		              							<image
		              								class="avatar"
		              								:src="item.type === 'location' ? '../../static/location.png' : item.icon || '../../static/default-avatar.png'"
		              								mode="aspectFill"
		              							></image>
		              						</view>
		              						<view class="name-msg-wrapper">
		              							<view class="name-row">
		              								<text class="name" >{{item.name}}</text>
		              								<text class="time" v-text="formatMessageTime(item.time)"></text>
		              							</view>
		              							<view class="address" >{{item.address}}</view>
		              							<view class="msg location-msg">
		              								<uni-icons type="map-pin" size="22" color="#55aaff" class="location-icon"></uni-icons>
		              								<text>离您{{ distanc(item.location) }}</text>
		              							</view>
		              						</view>
		              					</view>
		              				
		              			</scroll-view>
		              		</view>
		            </view>
		            <view v-show="current === 2">
		             	<!-- 好友列表 -->
		             		<view class="section">
		             			<view class="section-header">
		             				<view class="section-title">好友列表（{{ friendsList.length }}）</view>
		             				<view class="sort-actions">
		             					<text class="sort-btn" @click="getAddressBook">手机联系人</text>
		             					<text class="sort-btn" @click="handleSort('alpha')">A-Z</text>
		             				</view>
		             			</view>
		             			<scroll-view class="friends-list" scroll-y="true" :style="{ height: listHeight }">
		             				<view 
		             					class="friend-item" 
		             					v-for="(item, index) in friendsList" 
		             					:key="index" 
		             					@longpress="longpress" 
		             					@click="handleFriendClick(index)"
		             				>
		             					<view class="avatar-container">
		             						<image class="avatar" :src="item.customize_pic?item.customize_pic:item.nicPic.url" mode="aspectFill" lazy-load></image>
		             					</view>
		             					<view class="info">
		             						<view class="info-top">
		             							<text class="name" v-text="item.customize_name?item.customize_name:item.nicName"></text>
		             							<view v-if="item.isStick" class="stick-tag">置顶</view>
		             						</view>
		             						<view class="info-bottom">
		             							<text class="signature" v-text="item.signature || '暂无个性签名'"></text>
		             							<view class="phone-wrap">
		             								<uni-icons type="phone" size="22" color="#999"></uni-icons>
		             								<text class="phone" v-text="item.userTel ? item.userTel : '电话号码未公开'"></text>
		             							</view>
		             						</view>
		             					</view>
		             					<view class="edit">
		             						<image class="stick-icon" :src="item.isStick ? '/static/stick.png' : '/static/nostic.png'" mode="" @click.stop="stick(index)"></image>
		             						<button v-if="isEdit" type="warn" @click.stop="del(item)" class="delete-btn">删除</button>
		             						<image v-else class="top-icon" src="/static/toTop.png" mode="" @click.stop="toTop(index)"></image>
		             					</view>
		             				</view>
		             			</scroll-view>
		             		</view>
		            </view>
		        </view>


	</view>
</template>

<script>
// import { processReceivedMessage, initializeData } from '../../utils/chatList.js';
import formatMessageTime from '../../utils/formatMessageTime';
import { distance_m, distanceNum } from '../../utils/distance';
const db = uniCloud.databaseForJQL();
import {handleFriendRelation} from'@/utils/friend.js'
const linli = uniCloud.importObject('linliChat',{ customUI:true});
// 
export default {
	data() {
		return {
			checboxList: [],
			isDelFavorite: false,
			currentTab: '会话',
			isReadyNic: false,
			userId:"",
			avatarCache: {},
			chatListView: [],
			selcFavorList: [],
			chatList: [],
			unreadView: false,
			favorite_id:'',
			userInfos: [],
			isEdit: false,
			current:0,
			 items: ['最近会话', '收藏', '联系人'],
			msg_updata: [],
			isDelCount: false,
			user: {},
			favoriteList: [],
			groupList: [],
			friendsList: [],
			listHeight: '600rpx', // 动态计算的列表高度
			longPressTimer: null, // 长按定时器（防冲突）
			group: {
				groupInfo: { groupId: '', groupName: '', signature: '', groupPic: '', own: {} },
				groupSet: { isStick: false, online: false, customize_name: '', customize_pic: '' }
			},
			friend: {
				userSet: { isStick: false, online: false, customize_name: '', customize_pic: '' },
				userInfo: { userId: 3, nicName: '王五', nicPic: '/static/nicPic/m2.png', userTel: '131111111', signature: '全栈工程师' }
			}
		};
	},
	computed: {
		chatView() {
			if (!this.chatListView || !this.avatarCache) return [];
	
			return this.chatListView.map(item => {
				const pic = item.userId && this.avatarCache[item.userId] ? this.avatarCache[item.userId].pic : '/static/nicPic/nicDef.png';
				const name = item.userId && this.avatarCache[item.userId] ? this.avatarCache[item.userId].name : '匿名';
				let content = '';
				switch (item.lastMessage.messageType) {
					case 3: content = '图片信息'; break;
					case 2: content = item.lastMessage.content.text; break;
					case 1: content = '语音信息'; break;
					case 6: content = '视频信息'; break;
					case 4: content = '商品分享'; break;
					case 5: content = '商业分享'; break;
					default: content = '分享信息';
				}
				return { ...item, content, pic, name };
			}).sort((a, b) => b.lastMessage.timestamp - a.lastMessage.timestamp);
		},
		storeData() {
			return this.$store.state.msg;
		}
	},
	async mounted() {
		// 动态计算列表高度（减去顶部标题栏和底部Tab）
		const sysInfo = this.storeData.systemInfo;
		this.listHeight = `${sysInfo.windowHeight - 120}px`; // 120px = 240rpx（底部Tab高度）
	},
	async onLoad(res) {
		this.currentTab = res?.currentTab || '会话';
		this.user = this.storeData.user || {};
		this.favoriteList = await this.getFavorite(this.storeData.user?.favorite || []);
	
	},
async onShow() {
  this.friendsList = this.storeData.user.friends;

  
  // 1. 获取聊天初始化数据
  const chatInit = await initializeData();
  
  
  // 2. 关键：过滤掉 lastMessage 不存在的无效数据（核心修复）
  const validChatList = chatInit.filter(item => item?.lastMessage); // 只保留有 lastMessage 的数据
  
  // 3. 排序（此时数据均有 lastMessage，不会报错）
  this.chatList = validChatList.sort((a, b) => b.lastMessage.timestamp - a.lastMessage.timestamp);
  this.chatListView = this.chatList;
  
  // 后续加载头像逻辑不变
  await this.loadAvatars(this.chatList); // 传入过滤后的有效数据
  this.isReadyNic = true;
},
	methods: {
		formatMessageTime,
		// 长按处理（防点击冲突）
		handleLongPressChat(userId){
			this.isDelCount=!this.isDelCount
			this.userId=userId
		
		},
		onClickItem(e) {
		      if (this.current != e.currentIndex) {
		        this.current = e.currentIndex;
		      }},
		handleLongPress(id) {
			if(this.favorite_id===''){
				      this.favorite_id=id
			   this.isDelFavorite=true
			}else{
				this.favorite_id=''
				this.isDelFavorite=false
			}
         
		},
		// 排序处理
		handleSort(type) {
			if (type === 'time') {
				this.unreadView = false;
				this.chatListView = [...this.chatList].sort((a, b) => b.lastMessage.timestamp - a.lastMessage.timestamp);
			} else if (type === 'unread') {
				this.unreadView = !this.unreadView;
				this.chatListView = this.unreadView ? this.chatList.filter(item => item.unreadCount > 0) : this.chatList;
			} else if (type === '距离') {
				const list = [...this.favoriteList].sort((a, b) => {
					const locA = a.location || {};
					const locB = b.location || {};
					const userLoc = this.storeData.location || { longitude: 0, latitude: 0 };
					try {
						return distanceNum(userLoc, locA) - distanceNum(userLoc, locB);
					} catch (error) {
						console.error('排序时计算距离出错:', error);
						return 0;
					}
				});
				this.favoriteList = list;
			}
		},
		// 距离格式化
		distanc(item) {
			const loc1 = { longitude: item?.longitude || 0, latitude: item?.latitude || 0 };
			const userLoc = this.storeData.senderLocation || { longitude: 0, latitude: 0 };
			return distance_m(loc1, userLoc);
		},
		// 收藏点击处理
		handlefavorite(item) {
	
				this.$store.commit('msg/SET_isFly', true);
				this.$store.commit('msg/SET_location', item.location || {});
				uni.navigateTo({ url: '/pages/main/main' });
			
		},
		// 会话删除
		delCount() {
			try {
				const deledChatList = this.chatList.filter(item =>item.userId!==this.userId);
				console.log("4444",this.userId,deledChatList);
				this.chatListView = deledChatList;
				uni.setStorageSync('chatList', [deledChatList]);
				this.chatList = deledChatList;
			 
				this.isDelCount = false;
				uni.showToast({ title: '删除成功', icon: 'success' });
			} catch (e) {
				console.error('删除会话失败:', e);
				uni.showToast({ title: '删除失败', icon: 'none' });
			}
		},
	
		// 批量删除收藏（优化为批量接口调用）
		async handleDelfavo() {
		
			try {
				uni.showLoading({ title: '删除中...' });
				// 调用批量删除接口（需后端支持）
				const res = await linli.favorite({
					favorite_id:this.favorite_id,
					action: 'remove',
					userId: this.storeData.user?.userId
				});
                 console.log("55555555",res);
				if (res.code) {
					uni.hideLoading();
					uni.showToast({ title: '删除成功', icon: 'success' });
					this.$emit('refreshFavorites');
					this.selcFavorList = [];
					this.isDelFavorite = false;
					// 刷新本地列表
					this.favoriteList = this.favoriteList.filter(item => item.favorite_id!==this.favorite_id);
				    this.$store.dispatch('msg/getUserInfo')
					
					
				} else {
					throw new Error(res.message || '删除失败');
				}
			} catch (error) {
				uni.hideLoading();
				console.error('删除收藏失败:', error);
				uni.showToast({ title: `删除失败：${error.message}`, icon: 'none' });
			}
		},
		// 会话选择处理
		checkBox(e) {
			this.checboxList = e.target.value || [];
		},
		// 获取头像信息
		async fetchAvatarInfo(item) {
			try {
				let pic = '/static/nicPic/nicDef.png';
				let name = '匿名';
				let res;

				if (item.type === 'person' && item.userId) {
					res = await db.collection('linli-user').where({ userId: item.userId }).field({ nicPic: true, nicName: true }).get();
					if (res.data.length) {
						pic = res.data[0].nicPic || pic;
						name = res.data[0].nicName || item.userId;
					}
				} else if (item.type === 'group' && item.userId) {
					res = await db.collection('Group').where({ groupId: item.userId }).field({ groupPicPath: true, groupName: true }).get();
					if (res.data.length) {
						pic = res.data[0].groupPicPath || pic;
						name = res.data[0].groupName || '无名群';
					}
				}

				this.avatarCache[item.userId] = { pic, name };
			} catch (error) {
				console.error('获取头像失败:', error);
			}
		},
		// 加载头像
		async loadAvatars(res) {
			if (!res || !res.length) return;
			for (const item of res) {
				if (!this.avatarCache[item.userId]) {
					await this.fetchAvatarInfo(item);
				}
			}
		},
		// 切换Tab
		handleTabBar(id) {
			this.currentTab = id;
			uni.setNavigationBarTitle({ title: this.currentTab });
		},
		// 存储会话信息
		async stroe() {
			try {
				const res = await uni.getStorage({ key: 'sessions' });
				this.msg_updata = res.data || [];
			} catch (e) {
				await uni.setStorage({ key: 'sessions', data: [] });
				this.msg_updata = [];
			}
		},

		// 获取收藏列表
		async getFavorite(favorites = []) {
			try {
				if (!Array.isArray(favorites) || !favorites.length) return [];

				return await Promise.all(favorites.map(async item => {
					const uniqueKey = item.favorite_id || `${item.type}_${Date.now()}_${Math.random()}`;
					const obj = {
						...item,
						key: uniqueKey,
						icon: '../../static/default-avatar.png',
						name: item.name || '未命名收藏',
						time: item.createTime || Date.now(),
						location: item.location || {},
						favorite_id: item.favorite_id || uniqueKey
					};

					if (item.type === 'location') {
						obj.icon = '../static/location.png';
					} else if (item.type === 'group' && item.favorite_id) {
						try {
							const groupRes = await db.collection('Group').where({ groupId: item.favorite_id }).field({ groupPicPath: true }).get();
							obj.icon = groupRes.data[0]?.groupPicPath || obj.icon;
						} catch (e) {
							console.error(`获取群${item.favorite_id}头像失败:`, e);
						}
					}

					return obj;
				}));
			} catch (e) {
				console.error('处理收藏数据失败:', e);
				return [];
			}
		},
		// 合并数组
		mergeArrays(arr1, arr2, key) {
			const combined = [...arr1, ...arr2];
			const merged = combined.reduce((acc, current) => {
				const existingIndex = acc.findIndex(item => item[key] === current[key]);
				if (existingIndex > -1) acc[existingIndex] = current;
				else acc.push(current);
				return acc;
			}, []);
			const sorted = merged.sort((a, b) => b.latestMessageTime - a.latestMessageTime);
			this.msg_updata = sorted;
			uni.setStorageSync('sessions', sorted);
			return sorted;
		},
		// 长按进入编辑模式
		longpress() {
			this.isEdit = !this.isEdit;
		},
		// 删除联系人
	async	del(item) {
			try {
		   const res=  await 	handleFriendRelation(item,'del')
		   if(res.success){
			   this.friendsList=this.storeData.user.friends
			   uni.showToast({
			   	title:'删除好友成功',
				position:'center'
			   })
		   }
			} catch (e) {
				console.error('删除联系人失败:', e);
				uni.showToast({ title: '删除失败', icon: 'none' });
			}
		},
		/**
		 * 批量从数据库查询手机号对应的用户信息
		 * @param {Array} phoneList - 电话号码数组（如 ['13800138000', '13900139000']）
		 * @returns {Promise<Array>} - 用户信息数组（包含 userId、nicPic 等）
		 */
		async batchGetUserByPhone(phoneList) {
		  if (!Array.isArray(phoneList) || phoneList.length === 0) {
		    console.warn('批量查询手机号失败：参数必须是非空数组');
		    return [];
		  }
		
		  try {
		    // 使用 db.command.in() 批量查询，参数必须是数组
		    const res = await db.collection('linli-user')
		      .where({
		        userTel: db.command.in(phoneList) // 正确：传入电话号码数组
		      })
		      .field({
		        userId: true,
		        nicPic: true,
		        nicName: true,
		        userTel: true,
		        signature: true
		      })
		      .get();
		
		    return res.data || [];
		  } catch (error) {
		    console.error('批量从手机号获取用户信息失败:', error);
		    uni.showToast({ title: '获取联系人信息失败', icon: 'none' });
		    return [];
		  }
		},
		// 获取好友列表
		// async getfriend() {
		// 	try {
		// 		const addressBookTemp = await db.collection('addressBook').where({ userTel: this.storeData.user.useTel }).getTemp();
		// 		const { data } = await db.collection(addressBookTemp, 'linli-user').get();
		// 		this.friendsList = data.map(item => ({
		// 			userId: item.telePhone?.[0]?.userId || '',
		// 			customize_name: item.customize_name || item.telePhone?.[0]?.nicName || '未知用户',
		// 			customize_pic: item.customize_pic || item.telePhone?.[0]?.nicPic || '../../static/icon.png',
		// 			telePhone: this.areYouFriend(item.telePhone?.[0]?.userTel) ? item.telePhone?.[0]?.userTel : '',
		// 			isStick: !!item.isStick,
		// 			signature: item.signature || ''
		// 		}));
		// 	} catch (error) {
		// 		console.error('获取朋友列表失败:', error);
		// 	}
		// },
		// 检查是否为好友

		// 从手机号获取用户信息
	async getUserInfoFrom(tels) {
	    if (!tels || tels.length === 0) return [];
	    try {
	        const res = await db.collection('linli-user').where({ userTel: db.command.in(tels) }).field({ nicPic: true, userId: true }).get();
	        return res.data;
	    } catch (e) {
	        console.error('从手机号获取用户信息失败:', e);
	        uni.showToast({ title: '获取用户信息失败，请稍后再试', icon: 'none' });
	        return [];
	    }
	},
/**
 * 合并通讯录与现有好友列表（按 userId 去重）
 * @param {Array} existingList - 现有好友列表
 * @param {Array} newContacts - 新获取的通讯录联系人
 * @returns {Array} 合并后的列表
 */
mergeContacts(existingList, newContacts) {
  const existingUserIds = new Set(
    existingList.map(item => item.userId).filter(id => id) // 过滤空userId
  );

  // 只添加新联系人中不在现有列表的用户
  const uniqueNewContacts = newContacts.filter(contact => {
    // 非应用用户（无userId）全部保留，应用用户需判断是否已存在
    return !contact.userId || !existingUserIds.has(contact.userId);
  });

  return [...existingList, ...uniqueNewContacts];
},
		// 获取手机通讯录（多端适配）
		/**
		 * 获取手机通讯录并合并到好友列表（应用用户靠前排序）
		 */
		async getAddressBook() {
		  try {
		    // 1. 检查权限
		    const hasPermission = await this.checkContactsPermission();
		    if (!hasPermission) {
		      return uni.showToast({ title: '需要通讯录权限', icon: 'none' });
		    }
		
		    uni.showLoading({ title: '加载通讯录...' });
		    let contacts = [];
		
		    // 2. 按平台获取通讯录
		    // #ifdef APP-PLUS
		    const addressBook = await this.getAddressBookPromise();
		    contacts = await this.findContactsPromise(addressBook);
		    // #endif
		    // #ifdef MP-WEIXIN
		    const wxContacts = await wx.chooseContact();
		    contacts = [wxContacts]; // 微信单次选择一个
		    // #endif
		    // #ifdef H5
		    uni.showToast({ title: 'H5暂不支持通讯录', icon: 'none' });
		    uni.hideLoading();
		    return;
		    // #endif
		
		    // 3. 提取并格式化手机号（去重）
		    const phoneSet = new Set(); // 去重
		    contacts.forEach(item => {
		      if (item.phoneNumbers?.length) {
		        const phone = this.formatPhoneNumber(item.phoneNumbers[0].value);
		        if (phone) phoneSet.add(phone);
		      }
		    });
		    const phoneList = Array.from(phoneSet); // 转为数组
		
		    // 4. 批量查询应用内用户
		    const appUsers = await this.batchGetUserByPhone(phoneList);
		
		    // 5. 处理通讯录数据（标记应用用户）
		    const processedContacts = [];
		    contacts.forEach(item => {
		      if (item.phoneNumbers?.length) {
		        const phone = this.formatPhoneNumber(item.phoneNumbers[0].value);
		        if (!phone) return;
		
		        // 匹配应用内用户
		        const appUser = appUsers.find(u => u.userTel === phone);
		
		        processedContacts.push({
		          userId: appUser?.userId || '',
		          customize_name: item.displayName || '未知用户',
		          customize_pic: appUser?.nicPic || '../../static/icon.png',
		          userTel: phone,
		          isStick: false,
		          signature: appUser ? appUser.signature : '非本应用用户',
		          isAppUser: !!appUser // 标记是否为应用内用户
		        });
		      }
		    });
		
		    // 6. 合并到好友列表（去重）
		    this.friendsList = this.mergeContacts(this.friendsList, processedContacts);
		
		    // 7. 核心排序：应用用户靠前，非应用用户靠后
		    this.friendsList.sort((a, b) => {
		      // 优先级1：应用用户（true）排在非应用用户（false）前面
		      if (a.isAppUser && !b.isAppUser) return -1; // a在前
		      if (!a.isAppUser && b.isAppUser) return 1;  // b在前
		
		      // 优先级2：同为应用/非应用用户时，按名称拼音排序（可选）
		      const nameA = a.customize_name || a.nicName || '';
		      const nameB = b.customize_name || b.nicName || '';
		      return nameA.localeCompare(nameB, 'zh-CN'); // 中文拼音排序
		    });
		
		    uni.hideLoading();
		    uni.showToast({ 
		      title: `加载成功，发现 ${appUsers.length} 位应用用户`, 
		      icon: 'success' 
		    });
		  } catch (error) {
		    uni.hideLoading();
		    console.error('获取通讯录失败:', error);
		    const msg = error.message.includes('permission') ? '缺少权限' : '加载失败';
		    uni.showToast({ title: msg, icon: 'none' });
		  }
		},
		// 通讯录相关Promise封装
		getAddressBookPromise() {
			return new Promise((resolve, reject) => {
				plus.contacts.getAddressBook(0, resolve, reject);
			});
		},
		findContactsPromise(addressBook) {
			return new Promise((resolve, reject) => {
				addressBook.find(['displayName', 'phoneNumbers'], resolve, reject);
			});
		},
		// 检查通讯录权限
		checkContactsPermission() {
			return new Promise(resolve => {
				// #ifdef APP-PLUS
				plus.android.requestPermissions(
					['android.permission.READ_CONTACTS'],
					(resultObj) => {
						const granted = resultObj.granted || [];
						resolve(granted.includes('android.permission.READ_CONTACTS'));
					},
					() => resolve(false)
				);
				// #endif
				// #ifdef MP-WEIXIN
				wx.getSetting({
					success: res => {
						if (res.authSetting['scope.addressBook']) {
							resolve(true);
						} else {
							wx.authorize({ scope: 'scope.addressBook' })
								.then(() => resolve(true))
								.catch(() => resolve(false));
						}
					},
					fail: () => resolve(false)
				});
				// #endif
				// #ifdef H5
				resolve(false);
				// #endif
			});
		},
	
		// 格式化手机号
		formatPhoneNumber(phoneNumber) {
			if (!phoneNumber) return '';
			return phoneNumber.replace(/^\+86/, '').replace(/[\s-]/g, '');
		},
		// 置顶调整
		toTop(i) {
			if (i === 0) {
				return uni.showToast({ icon: 'none', title: '已经到顶了' });
			} else if (this.friendsList[i - 1]?.isStick) {
				return uni.showToast({ icon: 'none', title: '上面解锁后操作' });
			}
			// 交换位置
			const tmp = this.friendsList[i - 1];
			this.$set(this.friendsList, i - 1, this.friendsList[i]);
			this.$set(this.friendsList, i, tmp);
		},
		// 切换置顶状态
		stick(i) {
			this.$set(this.friendsList[i], 'isStick', !this.friendsList[i].isStick);
			uni.setStorageSync('addbooks', this.friendsList);
		},
		// 会话点击
		handleContactClick(id, type) {
			clearTimeout(this.longPressTimer); // 清除长按定时器
			if (type === 'person') {
				uni.navigateTo({ url: `/pages/PrivateChat/PrivateChat?id=${id}` });
			} else if (type === 'group') {
				uni.navigateTo({ url: `/pages/groupChat/groupChat?id=${id}` });
			}
		},
		// 联系人点击
		handleFriendClick(index) {
			const id = this.friendsList[index].userId||'';
			if(id){
				uni.navigateTo({
	    		url:`/pages/PrivateChat/PrivateChat?id=${id}`
	    	})	
			}else{
				uni.showToast({
			      title:'该用户尚未开通该服务',
				  icon:'none'
				})
			}
	    
		}
	}
};
</script>

<style lang="scss" scoped>
/* 变量定义 */
$spacing-sm: 16rpx;
$spacing-md: 24rpx;
$spacing-lg: 32rpx;
$font-sm: 24rpx;
$font-md: 28rpx;
$font-lg: 32rpx;
$color-primary: #09bb07;
$color-gray: #999;
$color-light-gray: #f5f5f5;
$color-border: #eee;
$radius-sm: 8rpx;
$radius-md: 16rpx;
$radius-lg: 24rpx;

/* 通用样式 */
.container {
	padding: 10rpx;
	background-color: $color-light-gray;
	min-height: 100vh;
	box-sizing: border-box;
}

/* 分区样式 */
.section {
	background: #fff;
	border-radius: $radius-md;
	margin-bottom: $spacing-md;
	padding: 0 $spacing-lg;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;

	&-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: $spacing-md 0;
		border-bottom: 2rpx solid $color-border;

		&-title {
			font-size: $font-lg;
			font-weight: 600;
			color: #333;
		}
	}
}

/* 排序按钮 */
.sort-actions {
	display: flex;
	gap: $spacing-sm;

	.sort-btn {
		font-size: $font-md;
		color: $color-gray;
		padding: 8rpx $spacing-sm;
		border-radius: $radius-sm;
		background: $color-light-gray;
		transition: all 0.2s ease;

		&:active {
			background: #eee;
			color: #666;
		}
	}

	.unread-btn.active {
		background-color: $color-primary;
		color: #fff;
	}

	.del-btn {
		background-color: #ff4444;
		color: #fff;

		&.disabled {
			background-color: #ffcccc;
			opacity: 0.6;
			cursor: not-allowed;
		}
	}

	.time-btn {
		background-color: $color-primary;
		color: #fff;
	}
}

/* 列表容器 */
.recent-list,
.friends-list {
	background-color: $color-light-gray;
	margin-bottom: 20rpx;
	border-radius: $radius-md;
	overflow: hidden;

	&::-webkit-scrollbar {
		width: 4rpx;
	}

	&::-webkit-scrollbar-thumb {
		background: #ddd;
		border-radius: 2rpx;
	}
}

/* 列表项 */
.recent-item,
.friend-item {
	padding: $spacing-md $spacing-sm;
	display: flex;
	align-items: center;
	background-color: #fff;
	border-radius: $radius-sm;
	margin: 0 1rpx 1rpx;
	transition: all 0.2s ease;
	cursor: pointer;

	&:active {
		background-color: $color-light-gray;
	}

	&.active {
		background-color: rgba(9, 187, 7, 0.1);
		border: 2rpx solid $color-primary;
	}
}

/* 头像容器 */
.avatar-container {
	width: 80rpx;
	height: 80rpx;
	position: relative;
	margin-right: $spacing-md;
	flex-shrink: 0;

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: $radius-md;
		object-fit: cover;
	}

	.avatar-loading {
		width: 100%;
		height: 100%;
		border-radius: $radius-md;
		background-color: $color-light-gray;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.badge {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		background: #ff4444;
		color: #fff;
		padding: 4rpx 12rpx;
		border-radius: 40rpx;
		font-size: $font-sm;
		min-width: 36rpx;
		text-align: center;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
	}
}

/* 名称-消息容器 */
.name-msg-wrapper {
	flex: 1;
	min-width: 0;

	.name-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;

		.name {
		
			font-size: $font-md;
			color: #333;
			font-weight: 500;
			max-width: 400rpx;
		}

		.time {
			font-size: $font-sm;
			color: $color-gray;
		}
	}

	.msg {
	
		font-size: $font-sm;
		color: $color-gray;

		&.unread {
			color: #333;
			font-weight: 500;
		}
	}

	.location-msg {
		display: flex;
		align-items: center;
		gap: 8rpx;
		color: #55aaff;
	}

	.location-icon {
		margin-top: 4rpx;
	}
}

/* 联系人信息区 */
.info {
	flex: 1;
	min-width: 0;

	.info-top {
		display: flex;
		align-items: center;
		gap: $spacing-sm;
		margin-bottom: 8rpx;

		.name {
		
			font-size: 30rpx;
			color: #333;
			font-weight: 600;
			max-width: 400rpx;
		}

		.stick-tag {
			font-size: $font-sm;
			color: $color-primary;
			background-color: rgba(9, 187, 7, 0.1);
			padding: 2rpx 12rpx;
			border-radius: 12rpx;
		}
	
	}

	.info-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.signature {
		
			font-size: $font-sm;
			color: $color-gray;
			max-width: 400rpx;
		}

		.phone-wrap {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: $font-sm;
			color: $color-gray;
		}
	}
}

/* 编辑区 */
.edit {
	display: flex;
	align-items: center;
	gap: $spacing-sm;
	flex-shrink: 0;

	.stick-icon,
	.top-icon {
		width: 50rpx;
		height: 50rpx;
		object-fit: contain;
	}

	.delete-btn {
		font-size: $font-sm;
		padding: 8rpx $spacing-sm;
		border-radius: $radius-sm;
		height: 60rpx;
		line-height: 60rpx;
	}
}
	.address{
		  font-size: 26rpx;
		  color: #a1a1a1;
		  font-weight: 500;
		  display: -webkit-box;
		  -webkit-line-clamp: 2;
		  -webkit-box-orient: vertical;
		  overflow: hidden;
		  line-height: 34rpx;
		  height: 64rpx; /* 固定高度，不撑开卡片 */
		  word-break: break-all;
		}
/* 复选框 */
.checkbox-label {
	margin-right: $spacing-sm;
	margin-left: 8rpx;
	flex-shrink: 0;
}

/* 底部Tab */
.tab-bar {
	display: flex;
	position: fixed;
	bottom: 0;
	background-color: #fff;
	left: 0;
	right: 0;
	height: 120rpx;
	border-top: 2rpx solid $color-border;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
	z-index: 999;

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 33.333%;
		height: 100%;
		transition: all 0.2s ease;

		.tab-text {
			font-size: $font-sm;
			margin-top: 8rpx;
			color: $color-gray;
			transition: all 0.2s ease;
		}

		&.active {
			.tab-text {
				color: $color-primary;
				font-weight: 500;
			}
		}
	}
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 400rpx;
	color: $color-gray;

	.empty-text {
		font-size: $font-md;
		margin-top: $spacing-sm;
	}

	.empty-tip {
		font-size: $font-sm;
		margin-top: 8rpx;
		color: #bbb;
	}
}

/* 骨架屏 */
.loading-skeleton {
	padding: $spacing-md;

	.skeleton-item {
		width: 100%;
		height: 120rpx;
		background-color: #fff;
		border-radius: $radius-sm;
		margin-bottom: $spacing-sm;
		background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
		background-size: 200% 100%;
		animation: skeleton-loading 1.5s infinite;
	}
}

@keyframes skeleton-loading {
	0% { background-position: 200% 0; }
	100% { background-position: -200% 0; }
}


</style>